﻿namespace TfsCloudDeploy.Workflow.Core.Activities
{
    using System.Activities;

    /// <summary>
    /// Reflected from: Microsoft.TeamFoundation.Build.Workflow.Activities.InvokeActionOnInput<T>.
    /// Assembly: Microsoft.TeamFoundation.Build.Workflow, Version=10.0.0.0.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    internal sealed class InvokeActionOnInput<T> : NativeActivity
    {
        // Methods
        protected override void CacheMetadata(NativeActivityMetadata metadata)
        {
            base.CacheMetadata(metadata);
            metadata.AddDefaultExtensionProvider<ScheduleActionExtension>(() => new ScheduleActionExtension());
        }

        protected override void Execute(NativeActivityContext context)
        {
            context.CreateBookmark(this.BookmarkName.Get(context), new BookmarkCallback(this.ItemReceived), BookmarkOptions.MultipleResume);
        }

        private void ItemReceived(NativeActivityContext context, Bookmark bookmark, object data)
        {
            if (data is T)
            {
                if (this.Action != null)
                {
                    context.ScheduleAction<T>(this.Action, (T)data, null, null);
                }
            }
            else if (data == ScheduleActionExtension.ShutdownEvent)
            {
                context.RemoveBookmark(bookmark);
            }
        }

        // Properties
        public ActivityAction<T> Action
        {
            get;
            set;
        }

        [RequiredArgument]
        public InArgument<string> BookmarkName
        {
            get;
            set;
        }

        protected override bool CanInduceIdle
        {
            get
            {
                return true;
            }
        }
    }
}
